import React from "react";
import { Button,Card,Col,Divider,Form,Icon,Input,notification,Row, Upload,DatePicker} from "antd";
import { loadNewsDetail, addNews,cateCascader } from "@/services/NewsCenter";
import moment from "moment";
import styles from "./styles.less";
import { formatMessage } from "umi-plugin-react/locale";
import Loading from "@/components/Loading";
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/index.css'

class NewsAddForm extends React.Component {
  constructor(props) {
    super(props);
    const id= props.id
    const type = props.type

    this.state = {
      loading: false, // 用户详细信息的加载状态，用户页面loading效果
      submiting: false, // 表单提交状态
      detail: {}, // 
      editorState: null,
      type:type,
      id 
    };
  }

  async componentDidMount() {

    this.loadData(this.state.id);
  }

  submitContent = async () => {
    const htmlContent = this.state.editorState.toHTML()
    const result = await saveEditorContent(htmlContent)

  }

  handleEditorChange = (editorState) => {
    const htmlContent = this.state.editorState.toHTML()
    this.setState({ editorState })
    this.setState({flow_content:htmlContent})
  }

  getHtmlContent = async e =>{
    return this.state.htmlContent
  }

  // 加载用户信息
  loadData = async id => {
    this.setState({ loading: true });
    loadNewsDetail(id)
      .then(res => {
        this.setState({
          detail:res,
          imageUrl: res.picture ? res.host + res.picture : null
        });
        const htmlContent = res ? res.content : ''

        this.setState({
          editorState: BraftEditor.createEditorState(htmlContent)
        })
        
      })
      .finally(() => {
        this.setState({
          loading: false
        });
      });

  };

  handleSubmit = async e => {
    e.preventDefault();
    if (this.submiting) {
      return;
    }
    // setState为异步动作，直接设置submiting变量作为限制
    this.submiting = true;
    this.setState({
      submiting: true
    });
    this.props.form.validateFields(async (err, fieldsValue) => {
      if (err) {
        this.submiting = false;
        this.setState({
          submiting: false
        });
        return;
      }
      console.log(fieldsValue)
      let content = this.state.editorState.toHTML();
      const params = {
        id: this.state.id,
        type:this.state.type,
        title:fieldsValue.title,
        picture:this.state.picture,
        content: content,
        add_date:fieldsValue.add_date ? fieldsValue.add_date.format("YYYY-MM-DD") : null,
        sort:fieldsValue.sort,
      };

      addNews(params).then(res => {
        this.submiting = false;
        this.setState({
          submiting: false
        });
        if (res && res.status !== 200) {
        } else {
          notification.success({
            message: "添加成功"
          });
          this.props.handleAddCancel();
          this.props.refresh();
        }
      });
    });
  };

  // ------------上传图片---------------
  beforeUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只支持上传jpg或者png的图片!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能大于2MB!');
    }
    return isJpgOrPng && isLt2M;
  }

  getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  handleChange = info => {
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, imageUrl =>
        this.setState({
          imageUrl,
          picture:info.file.response,
          loading: false,
        }),
      );
    }
  };

  removePicture = e => {
    this.setState({
      imageUrl: null,
      picture:null,
    })
  }

  onCateChange = e =>{
    this.setState({cate:e})
  }

  


  render() {
    const { getFieldDecorator } = this.props.form;
    const { submiting,editorState,imageUrl } = this.state;

    const titleExtraButton = (
      <Row type="flex" gutter={12} align="middle">
        <Col>
          <Button
            type="primary"
            loading={submiting}
            onClick={this.handleSubmit}
          >
            提交
          </Button>
        </Col>
        <Col>
          <Button onClick={this.props.handleAddCancel}>返回</Button>
        </Col>
      </Row>
    );


    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        {/* <div style={{ marginTop: 8 }}>Upload</div> */}
      </div>
    );

    const myUploadFn = (param) => {

      const serverURL = '/api/admin/uploadImage'
      const xhr = new XMLHttpRequest
      const fd = new FormData()
    
      const successFn = (response) => {
        // 假设服务端直接返回文件上传后的地址
        // 上传成功后调用param.success并传入上传后的文件地址
        param.success({
          url: xhr.responseText,
        })
      }
    
      const progressFn = (event) => {
        // 上传进度发生变化时调用param.progress
        param.progress(event.loaded / event.total * 100)
      }
    
      const errorFn = (response) => {
        // 上传发生错误时调用param.error
        param.error({
          msg: 'unable to upload.'
        })
      }
    
      xhr.upload.addEventListener("progress", progressFn, false)
      xhr.addEventListener("load", successFn, false)
      xhr.addEventListener("error", errorFn, false)
      xhr.addEventListener("abort", errorFn, false)
    
      fd.append('file', param.file)
      xhr.open('POST', serverURL, true)
      xhr.send(fd)
    
    }

    const { detail, loading} = this.state;

    const rowGutter = [16, 16];

    function displayRender(label) {
      return label[label.length - 1];
    }    
    return (
      <Card>
        {loading ? (
          <Loading />
        ) : (
          <Form labelCol={{ span: 4 }}
          wrapperCol={{ span: 14 }}
          layout="horizontal">
            <Divider orientation="left" dashed>
              {/* <span style={{ fontSize: 12 }}>详细信息</span> */}
            </Divider>
            
            <Row type="flex" gutter={rowGutter}>
              <Col span={24}>
                <Row gutter={rowGutter}>
                  <Col span={24}>
                    <Form.Item label="新闻标题">
                      {getFieldDecorator("title", {
                        initialValue: detail.title?detail.title:'',
                        rules: [
                          {
                            required: true,
                            message: formatMessage({
                              id: "请输入新闻标题"
                            })
                          }
                        ]
                      })(<Input style={{width: 400 }} />)}
                    </Form.Item>
                  </Col>
                </Row>

                <Form.Item
                  label="新闻缩略图"
                  valuePropName="fileList"
                  extra="支持jpg/png格式，不得大于2M，建议尺寸350px*197px"
                >
                  <Row>
                    <Col span={6}>
                      <Upload
                          name="news_picture"
                          listType="picture-card"
                          className="avatar-uploader"
                          showUploadList={false}
                          action="/api/admin/uploadImage"
                          beforeUpload={this.beforeUpload}
                          onChange={this.handleChange}      
                        >
                          {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                      </Col>
                      {imageUrl ?
                        <Col style={{marginTop: '10%'}}>
                          <Button shape="circle" icon="delete" onClick={this.removePicture}/>
                        </Col>
                        :null}
                    </Row>
                </Form.Item>

                <Row gutter={rowGutter}>
                  <Col span={24}>
                    <Form.Item label="发布日期">
                      {getFieldDecorator("add_date", {
                        initialValue: detail.add_date ? moment(detail.add_date) : moment(),
                      })(<DatePicker onChange={this.onChange} format={'YYYY-MM-DD'}/>)}
                    </Form.Item>
                  </Col>
                </Row>

                <Row gutter={rowGutter}>
                  <Col span={24}>
                    <Form.Item label="排序" help="数值越大排序越靠前">
                      {getFieldDecorator("sort", {
                        initialValue: detail.sort?detail.sort:0,
                      })(<Input style={{width: 200 }} />)}
                    </Form.Item>
                  </Col>
                </Row>

                <Row>
                  <Col span={24}>
                    <Form.Item label="新闻内容">
                    
                    </Form.Item>
                    <div className="my-component" style={{marginLeft:'110px',border:'1px solid #ccc'}}>
                      <BraftEditor
                        value={editorState}
                        onChange={this.handleEditorChange}
                        onSave={this.submitContent}
                        media={{uploadFn: myUploadFn}}
                        imageResizable={false}
                      />
                    </div>
                  </Col>
                </Row>

              </Col>
            </Row>

            <Row gutter={rowGutter}>
              <Col span={24} style={{marginLeft:'110px',marginTop:'20px'}}>
                {titleExtraButton}
              </Col>
            </Row>
          </Form>
        )}
      </Card>
    );
  }
}

const WrappedNewsAddForm = Form.create({ name: "News_add" })(
  NewsAddForm
);
export default WrappedNewsAddForm;
